/*
 * @Autor: zwf
 * @Date: 2022-09-05 21:28:51
 * @Version: 1.0
 * @Description: sessionStorage封装
 **/

export default class Session {
  // 本地存储前缀
  prefix = "test_";
  /*
   *@method 写入存储
   *@param  string  name    key
   *@param  any     value   混合类型
   *@param  string  prefix  前缀
   *@return
   */
  set(name, value, prefix = "") {
    let keys = this.prefix + name;
    if (prefix) {
      keys = prefix + name;
    }
    const data = {
      data: value,
    };
    try {
      sessionStorage.setItem(keys, JSON.stringify(data));
      return true;
    } catch (error) {
      return false;
    }
  }
  /*
   *@method 判断key是否存在
   *@param  string  name  key
   *@param  string  prefix  前缀
   *@return
   */
  has(name, prefix = "") {
    let keys = this.prefix + name;
    if (prefix) {
      keys = prefix + name;
    }
    if (sessionStorage.getItem(keys) == null) {
      return false;
    }
    return true;
  }
  /*
   *@method 获取本地存储
   *@param  string  name  key
   *@param  string  prefix  前缀
   *@return
   */
  get(name, prefix = "") {
    let keys = this.prefix + name;
    if (prefix) {
      keys = prefix + name;
    }
    let json = sessionStorage.getItem(keys) || "";
    const data = json ? JSON.parse(json) : { data: "" };
    return data.data;

  }
  /*
   *@method 移除本地存储
   *@param  string name key
   *@param  string  prefix  前缀
   *@return
   */
  remove(name, prefix = "") {
    let keys = this.prefix + name;
    if (prefix) {
      keys = prefix + name;
    }
    return sessionStorage.removeItem(keys);
  }
  /*
   *@method 移除全部本地存储
   *@return
   */
  clear() {
    sessionStorage.clear();
  }
}
